package com.example.online_search_springboot.searcher;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//通过这个类在内存中构造出索引
public class Index {
    //新建俩个锁对象
    private Object locker1 = new Object();
    private Object locker2 = new Object();
    // /usr/sofrwares_tl/tomcat_1109/tomcat_8.5/online_search_doc/
    private static String INDEX_PATH = null;

    static {
        if (Config.isOnline) {
            INDEX_PATH = "src/main/resources/static/online_search_doc/";
        } else {
            INDEX_PATH = "C:/Users/Administrator/Desktop/online_search_doc/";
        }
    }

    private ObjectMapper objectMapper = new ObjectMapper();
    private ArrayList<DocInfo> forwardIndex = new ArrayList<>();

    private HashMap<String, ArrayList<Weight>> invertedIndex = new HashMap<>();

    //给定一个docId,在正排索引中，查询文档的详细信息
    public DocInfo getDocInfo(int docId) {
        return forwardIndex.get(docId);
    }

    //给定一个词，在倒排索引中，查哪些文档和这个词相关联
    public List<Weight> getInverted(String term) {
        return invertedIndex.get(term);
    }

    //往索引中新增一个文档
    public void addDoc(String title, String url, String content) {
        //构建正排索引
        DocInfo docInfo = buildForward(title, url, content);
        //构建倒排索引
        buildInverted(docInfo);
    }

    private void buildInverted(DocInfo docInfo) {
        class WordCnt {
            public int titleCount;
            public int contentCount;
        }

        HashMap<String, WordCnt> wordCntHashMap = new HashMap<>();

        List<Term> terms = ToAnalysis.parse(docInfo.getTitle()).getTerms();

        for (Term term : terms) {
            String word = term.getName();
            WordCnt wordCnt = wordCntHashMap.get(word);
            if (wordCnt == null) {
                WordCnt newWordCnt = new WordCnt();
                newWordCnt.titleCount = 1;
                wordCntHashMap.put(word, newWordCnt);
            } else {
                wordCnt.titleCount += 1;
            }

        }

        terms = ToAnalysis.parse(docInfo.getContent()).getTerms();

        for (Term term : terms) {
            String word = term.getName();
            WordCnt wordCnt = wordCntHashMap.get(word);
            if (wordCnt == null) {
                WordCnt newWordCnt = new WordCnt();
                newWordCnt.contentCount = 1;
                wordCntHashMap.put(word, newWordCnt);
            } else {
                wordCnt.contentCount += 1;
            }

        }

        for (Map.Entry<String, WordCnt> entry : wordCntHashMap.entrySet()) {
            //倒排拉链 invertedList
            synchronized (locker2) {
                ArrayList<Weight> invertedList = invertedIndex.get(entry.getKey());

                if (invertedList == null) {
                    ArrayList<Weight> newInvertedList = new ArrayList<>();
                    Weight weight = new Weight();
                    weight.setDocId(docInfo.getDocId());
                    weight.setWeight(entry.getValue().titleCount * 10 + entry.getValue().contentCount);
                    newInvertedList.add(weight);
                    invertedIndex.put(entry.getKey(), newInvertedList);
                } else {
                    Weight weight = new Weight();
                    weight.setDocId(docInfo.getDocId());
                    weight.setWeight(entry.getValue().titleCount * 10 + entry.getValue().contentCount);
                    invertedList.add(weight);
                }
            }
        }
    }

    private DocInfo buildForward(String title, String url, String content) {
        DocInfo docInfo = new DocInfo();

        docInfo.setTitle(title);
        docInfo.setUrl(url);
        docInfo.setContent(content);
        synchronized (locker1) {//this指代index这个实例
            docInfo.setDocId(forwardIndex.size());
            forwardIndex.add(docInfo);
        }
        return docInfo;
    }

    //把内存中的索引结构保存到磁盘中
    public void save() {
        long begin = System.currentTimeMillis();
        System.out.println("保存索引开始！");
        File indexPathFile = new File(INDEX_PATH);
        if (!indexPathFile.exists()) {
            indexPathFile.mkdirs();
        }
        File forwardIndexFile = new File(INDEX_PATH + "forward.txt");
        File invertedIndexFile = new File(INDEX_PATH + "inverted.txt");
        try {
            objectMapper.writeValue(forwardIndexFile, forwardIndex);
            objectMapper.writeValue(invertedIndexFile, invertedIndex);
        } catch (IOException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("保存索引完成！消耗时间：" + (end - begin) + " ms");

    }

    //把磁盘中的索引数据加载到内存中
    public void load() {
        long begin = System.currentTimeMillis();
        System.out.println("加载索引开始！");
        File forwardIndexFile = new File(INDEX_PATH + "forward.txt");
        File invertedIndexFile = new File(INDEX_PATH + "inverted.txt");
        try {
            forwardIndex = objectMapper.readValue(forwardIndexFile, new TypeReference<ArrayList<DocInfo>>() {
            });
            invertedIndex = objectMapper.readValue(invertedIndexFile, new TypeReference<HashMap<String, ArrayList<Weight>>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("加载索引结束！消耗时间：" + (end - begin) + " ms");
    }
}
